package com.ruoyi.study.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.constant.HttpStatusEnum;
import com.ruoyi.common.core.exception.BizException;
import com.ruoyi.study.domain.StyRedis;
import com.ruoyi.study.mapper.StyRedisMapper;
import com.ruoyi.study.service.IStyRedisStudyService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.ruoyi.study.tool.redis.RedisConstants.CACHE_REDIS_KEY;

/**
 * redis信息Service业务层处理
 * 
 * @author dwb
 * @date 2024-09-04
 */
@Service
public class StyRedisStudyServiceImpl implements IStyRedisStudyService
{

    @Resource
    private StyRedisMapper styRedisMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public StyRedis styRedisCache(Long id) {
        //在Redis查询缓存是否存在
        //styRedisMapper.selectStyRedisById(id);
        String redisJson = stringRedisTemplate.opsForValue().get(CACHE_REDIS_KEY + id);
        //判断是否存在
        if(StrUtil.isNotBlank(redisJson)){
            //存在返回
            StyRedis styRedis = JSONUtil.toBean(redisJson, StyRedis.class);
            return styRedis;
        }
        //不存在查询数据库
        StyRedis styRedis = styRedisMapper.selectStyRedisById(id);
        //不存在返回null
        if (styRedis == null) {
            throw new BizException(HttpStatusEnum.DATA_NOT_EXIST.getStatus(), "数据不存在");
        }
        //存在缓存到redis
        stringRedisTemplate.opsForValue().set(CACHE_REDIS_KEY + id, JSONUtil.toJsonStr(styRedis));

        return styRedis;
    }
}
